<?php
namespace app\common\model;
use app\common\traits\Models;
use think\Model;
use think\facade\{
    App,Request,Config
};
class ComCodephone extends Model
{
    use Models;
    protected $readonly = [];
    protected $auto     = [];
    protected $insert   = ['ip','token','end_time'];
    protected $update   = [];

    //设置Ip
    protected function setIpAttr()
    {
        return Request::ip(1);
    }

    //设置token
    protected function setTokenAttr()
    {
        return com_token();
    }

    //设置过期时间
    protected function setEndTimeAttr()
    {
        return Request::time()+Config::get('type.expire_time');
    }

    /**
     * 发送短信
     * @param  [type] $phone [手机号码]
     * @return [type]        [description]
     */
    public function sendSms($phone){
        $code = rand(1000,9999);
        $data = ['phone'=>$phone,'code'=>$code];
        $validate = App::validate('ComCodephone');
        if (!$validate->check($data)) {
            $this->error = $validate->getError();// 验证失败 输出错误信息
            return false;
        }
        $model = $this::create($data);
        //todo:发送短信

        //xls 临时返回code
        return [$model->token,$model->code];
    }

    /**
     * 验证短信
     * @param  [type] $phone [手机号码]
     * @param  [type] $phone_token [token]
     * @param  [type] $code  [验证码]
     * @return [type]        [description]
     */
    public function checkCode($phone, $phone_token, $code){
        $rs = $this::get(function($query)use($phone, $phone_token,$code){
            $query->where([['phone','=',$phone],['token','=',$phone_token],['code','=',$code],['end_time','>',Request::time()]]);
        });
        if($rs){
            $rs->delete(true);
            return true;
        }
        $this->error = '短信验证码错误';
        return false;
    }
}
